﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data;
using IRepository;
using OA.DataBase;

namespace RepositoryImp
{
    public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class
    {
        protected OAContext dbContext;
        protected DbSet<TEntity> dbSet;

        public BaseRepository(OAContext p_dbContext)
        {
            dbContext = p_dbContext;
            dbSet = p_dbContext.Set<TEntity>();
        }

        public void Insert(TEntity entity)
        {
            dbSet.Add(entity);
        }

        public virtual void Delet(TEntity entity)
        {
            if (dbContext.Entry(entity).State == EntityState.Detached)
            {
                dbSet.Attach(entity);
            }
            dbSet.Remove(entity);
        }

        public void Update(TEntity entity)
        {
            dbSet.Attach(entity);
            dbContext.Entry(entity).State = EntityState.Modified;
        }

        public TEntity Load(params object[] keyValues)
        {
            return dbSet.Find(keyValues);
        }

        public virtual List<TEntity> All()
        {
            return dbSet.ToList();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="query"></param>
        /// <param name="parameters"></param>
        /// var query = "SELECT * FROM Course WHERE CourseID = @p0";
        /// <returns></returns>
        public IEnumerable<TEntity> GetWithRawSql(string query, params object[] parameters)
        {
            return dbSet.SqlQuery(query, parameters);
        }


        public IEnumerable<TEntity> Get(System.Linq.Expressions.Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "")
        {
            IQueryable<TEntity> query = dbSet;
            if (filter != null)
            { query = query.Where(filter); }
            foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            { query = query.Include(includeProperty); }
            if (orderBy != null)
            { return orderBy(query).ToList(); }
            else
            { return query.ToList(); }
        }
    }
}
